﻿using System;
using System.ServiceModel;
using System.Web.Mvc;
using System.Web.Security;
using Aidbrella.Web.ViewModels;
using AidbrellaWCFProxy.aidBrellaService;

namespace Aidbrella.Web.Controllers
{
	public partial class AccountController : BaseController
	{
		[HttpGet]
		public virtual ActionResult LogOn()
		{
			if (User.Identity.IsAuthenticated)
			{
				return RedirectToAction("Index", "Home");
			}
			return View();
		}

		[HttpGet]
		public virtual ActionResult LogOut()
		{
			FormsAuthentication.SignOut();
			return RedirectToAction("Index", "Home");
		}

		[HttpPost]
		public virtual ActionResult LogOn(UserViewModel model)
		{
			if (Membership.ValidateUser(model.UserName, model.Password))
			{
				FormsAuthentication.RedirectFromLoginPage(model.UserName, true);
			}
			ModelState.AddModelError("Password", "Username or password was incorrect");
			return View(model);
		}

		//Get: /Register
		public virtual ActionResult Register()
		{
			var register = new UserRegisterViewModel();
			return View(register);
		}

		[HttpPost]
		public virtual ActionResult Register(UserRegisterViewModel regModel)
		{
			if (regModel == null)
			{
				return View(new UserRegisterViewModel());
			}

			if (!IsUsernameAvailable(regModel.NewUser.UserName))
			{
				ModelState.AddModelError("NewUser.UserName", "User Name already exists");
			}

			if (!string.Equals(regModel.ConfirmPassword, regModel.NewUser.Password, StringComparison.InvariantCulture))
			{
				ModelState.AddModelError("ConfirmPassword", "Passwords didn't match");
			}

			if (CreateMembershipUser(regModel))
			{
				CreateAidbrellaUser(regModel);

				return RedirectToAction("Logon", "Account");
			}

			return View(regModel);
		}

		private void CreateAidbrellaUser(UserRegisterViewModel regModel)
		{
			var client = new AidBrellaServiceClient();
			try
			{
				client.CreateUser(regModel.NewUser.UserName, regModel.NewUser.FirstName, regModel.NewUser.LastName, regModel.NewUser.Email);
			}
			catch (Exception)
			{
				client.Abort();
				throw;
			}
			finally
			{
				if (client.State != CommunicationState.Closed)
					client.Close();
			}
		}

		private bool IsUsernameAvailable(string username)
		{
			return Membership.FindUsersByName(username).Count == 0;
		}

		private bool CreateMembershipUser(UserRegisterViewModel regModel)
		{
			try
			{
				Membership.CreateUser(regModel.NewUser.UserName, regModel.NewUser.Password, regModel.NewUser.Email);
				return true;
			}
			catch (MembershipCreateUserException ex)
			{
				if (ex.StatusCode == MembershipCreateStatus.InvalidPassword)
				{
					ModelState.AddModelError("NewUser.Password", ex.Message);
				}
				else if (ex.StatusCode == MembershipCreateStatus.InvalidUserName)
				{
					ModelState.AddModelError("NewUser.UserName", ex.Message);
				}
				else if (ex.StatusCode == MembershipCreateStatus.InvalidEmail)
				{
					ModelState.AddModelError("NewUser.Email", ex.Message);
				}
				return false;
			}
		}
	}
}
